package cn.jd.org.service.impl;


import cn.jd.basic.service.impl.BasicServiceImpl;

import cn.jd.org.domain.Department;
import cn.jd.org.domain.Employee;
import cn.jd.org.mapper.DepartmentMapper;

import cn.jd.org.service.DepartmentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BasicServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> findDeptree() {
        List<Department> allDepts = departmentMapper.findAll();
        List<Department> result = new ArrayList<>();
       if(CollectionUtils.isEmpty(allDepts)){
           return result;
       }
        // 用Stream流将集合转成map
       Map<Long, Department> collect = allDepts.stream().collect(Collectors.toMap(Department::getId, dept -> dept));

        // 组装数据
        for (Department dept : allDepts) {
            if (null != dept.getParentId()){
              Department parent = collect.get(dept.getParentId());
                if(parent==null){
                    break;
                }
                parent.getChildren().add(dept);
                 /*for (Department parent : allDepts) {
                     if (dept.getParentId().equals(parent.getId())){
                       parent.getChildren().add(dept);
                       break;
                    }
                }*/
            }else {
                result.add(dept);
            }
        }
        return result;
    }


    @Override
    public List<Employee> findDeptdeptemployee(Long id) {
        return departmentMapper.findDeptdeptemployee(id);
    }

    @Override
    public void removeAll(Long id) {
        System.out.println(id);
        List<Department> departmentall = departmentMapper.findAll();
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        List<Department> list = createTree(id, departmentall);
        for (Department department : list) {
            ids.add(department.getId());
        }
        System.out.println(ids);
        // 组装数据

        /*System.out.println(ids+"ids123");*/
      /* departmentMapper.deleteByAll(ids);*/
    }
    private List<Department> createTree(Long id, List<Department> departmentall) {
        List<Department> deptar = new ArrayList<>();
        for (Department dept : departmentall) {
            if (id == dept.getParentId()) {
                deptar.add(dept);
                dept.setChildren(createTree(dept.getId(), departmentall));
            }
        }
        return deptar;
    }

}
